package com.wzh.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wzh.common.utils.HttpUtils;
import com.wzh.mall.member.dao.MemberLevelDao;
import com.wzh.mall.member.entity.MemberLevelEntity;
import com.wzh.mall.member.exception.PhoneExistException;
import com.wzh.mall.member.exception.UsernameExistException;
import com.wzh.mall.member.vo.MemberLoginVo;
import com.wzh.mall.member.vo.MemberRegistVo;
import com.wzh.mall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.common.utils.PageUtils;
import com.wzh.common.utils.Query;

import com.wzh.mall.member.dao.MemberDao;
import com.wzh.mall.member.entity.MemberEntity;
import com.wzh.mall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao levelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) throws   PhoneExistException, UsernameExistException{

           MemberDao memberDao = this.baseMapper;

           MemberEntity memberEntity = new MemberEntity();
           // 设置默认等级
           MemberLevelEntity levelEntity=levelDao.getDefaultLevel();
           memberEntity.setLevelId(levelEntity.getId());
           // 设置其他
           // 检查用户名和手机号是否唯一 为了能让controller感知异常 我们需要让异常机制来抛出异常
           checkPhoneUnique(vo.getPhone());
           checkUsernameUnique(vo.getUsername());
           memberEntity.setMobile(vo.getPhone());
           memberEntity.setUsername(vo.getUsername());
           memberEntity.setNickname(vo.getUsername());
           // 设置密码 密码要进行加密存储
           // MD5盐值加密
           BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
           String encode = passwordEncoder.encode(vo.getPassword());
           memberEntity.setPassword(encode);
           // 其他的默认信息
           memberDao.insert(memberEntity);

    }

    @Override
    public void checkPhoneUnique(String phone)  throws PhoneExistException{
        MemberDao baseMapper = this.baseMapper;
        Integer integer = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (integer>0){
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        MemberDao baseMapper = this.baseMapper;
        Integer integer = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (integer>0){
            throw new UsernameExistException();
        }


    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {

        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        // 去数据库查询 SELECT * FROM `ums_member` WHERE usernane=? OR mobile=?
        MemberDao baseMapper = this.baseMapper;
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if (memberEntity==null){
            // 登陆失败
            return null;
        }else {
            // 获取到数据库的password字段 $2a$10$XpTqyu6QeR75aGlXLDGSFO.Wp36bkbcvdz284Ui9BSc1KqmnbQ4dW
            String passwordDb = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            // 进行密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if (matches){
                return memberEntity;
            }else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        // 具有登陆和注册合并逻辑
        String uid = socialUser.getUid();
        // 判断当前社交用户是否已经登陆过系统
        MemberDao baseMapper = this.baseMapper;
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity!=null){
            // 用户之前注册过 更新过期时间
            MemberEntity entity = new MemberEntity();
            entity.setId(memberEntity.getId());
            entity.setAccessToken(socialUser.getAccess_token());
            entity.setExpiresIn(socialUser.getExpires_in());

            baseMapper.updateById(entity);

            memberEntity.setExpiresIn(socialUser.getExpires_in());
            memberEntity.setAccessToken(socialUser.getAccess_token());
            return memberEntity;
        }else {
            // 用户没有注册 需要先进行注册
            MemberEntity memberEntity1 = new MemberEntity();
            try{
                // 查出当前社交账户信息（昵称，性别等）
                HashMap<String, String> query = new HashMap<>();
                query.put("access_token",socialUser.getAccess_token());
                query.put("uid",socialUser.getUid());
                HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/2/users/show.json",
                        "get", new HashMap<String, String>(), query, new HashMap<String, String>());

                if (response.getStatusLine().getStatusCode()==200) {
                    // 查询成功
                    String s = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(s);

                    // 按个获取个人信息
                    // 昵称
                    String name = jsonObject.getString("name");
                    // 性别
                    String gender = jsonObject.getString("gender");
                    //...........

                    // 将上述信息设置进行用户信息中
                    memberEntity1.setUsername(name);
                    memberEntity1.setGender("m".equals(gender) ? 1 : 0);
                    // ..........

                }
            }catch (Exception e){

            }
            memberEntity1.setSocialUid(socialUser.getUid());
            memberEntity1.setAccessToken(socialUser.getAccess_token());
            memberEntity1.setExpiresIn(socialUser.getExpires_in());
            baseMapper.insert(memberEntity1);

            return memberEntity1;
        }
    }

}